package com.hymall.
        service.admin;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hymall.bean.*;
import com.hymall.bean.bo.AddGoodBO;
import com.hymall.bean.bo.AdminSearchBO;
import com.hymall.bean.bo.AdminUPDataBO;
import com.hymall.bean.common.BasePageInfo;
import com.hymall.bean.common.CommonData;
import com.hymall.bean.common.PicURL;
import com.hymall.bean.vo.*;
import com.hymall.mapper.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;

/**
 * @Author: haiyuny
 * @Date: 2022/7/17 10:43
 * @Description:
 */
@Service
public class GoodsServiceImpl implements GoodsService {
    @Autowired
    MarketGoodsMapper marketGoodsMapper;
    @Autowired
    MarketGoodsAttributeMapper attributeMapper;
    @Autowired
    MarketGoodsSpecificationMapper specificationMapper;
    @Autowired
    MarketGoodsProductMapper productMapper;
    @Autowired
    MarketBrandMapper brandMapper;
    @Autowired
    MarketCategoryMapper categoryMapper;
    @Autowired
    MarketStorageMapper storageMapper;
    @Autowired
    MarketCommentMapper commentMapper;
    @Autowired
    MarketKeywordMapper keywordMapper;

    /*
     * @author 李海云
     * @description 评论删除
     * @date 2022/7/18 9:06
     * @param comment
     * @return
     */
    @Override
    public void deleteComment(MarketComment comment) {
        System.out.println(comment.getValueId());
        MarketCommentExample mce = new MarketCommentExample();
        mce.createCriteria().andValueIdEqualTo(comment.getValueId());
        commentMapper.deleteByExample(mce);
        comment.setDeleted(true);
        commentMapper.insert(comment);
    }


    /*
     * @author 李海云
     * @description 评论
     * @date 2022/7/18 9:06
     * @param
     * @return CommonData
     */
    @Override
    public CommonData queryCommentList(BasePageInfo info, AdminSearchBO search) {

        PageHelper.startPage(info.getPage(), info.getLimit());
        MarketCommentExample marketCommentExample = new MarketCommentExample();
        marketCommentExample.setOrderByClause(info.getSort());
        MarketCommentExample.Criteria criteria = marketCommentExample.createCriteria();
        criteria.andDeletedEqualTo(false);

        if (search.getName() != null) {
            criteria.andUserIdEqualTo(search.getUserId());
        }
        if (search.getGoodsSn() != null) {
            criteria.andValueIdEqualTo(search.getValueId());
        }


        List<MarketComment> marketComments = commentMapper.selectByExample(marketCommentExample, info.getOrder());
        PageInfo<MarketComment> pageInfo = new PageInfo<>(marketComments);
        return CommonData.data(pageInfo);

    }

    /*
     * @author 李海云
     * @description 商品首页
     * @date 2022/7/18 9:06
     * @param
     * @return CommonData 商品展示列表信息
     */
    @Override
    public CommonData queryGoodsList(BasePageInfo info, AdminSearchBO search) {

        if (info.getLimit() == 0 && info.getSort() == null & info.getPage() == null && info.getSort() == null) {
            MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
            MarketGoodsExample.Criteria criteria = marketGoodsExample.createCriteria();
            criteria.andDeletedEqualTo(false);
            List<MarketGoods> marketGoods = marketGoodsMapper.selectByExample(marketGoodsExample, info.getOrder());
            PageInfo<MarketGoods> pageInfo = new PageInfo<>(marketGoods);
            pageInfo.setPages(0);
            pageInfo.setPageNum(0);
            return CommonData.data(pageInfo);
        }

        PageHelper.startPage(info.getPage(), info.getLimit());
        MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
        marketGoodsExample.setOrderByClause(info.getSort());
        MarketGoodsExample.Criteria criteria = marketGoodsExample.createCriteria();
        criteria.andDeletedEqualTo(false);

        if (search.getName() != null) {
            criteria.andNameLike("%" + search.getName() + "%");
            // criteria.andNameEqualTo(search.getName());
        }
        if (search.getGoodsSn() != null) {
            criteria.andGoodsSnEqualTo(search.getGoodsSn());
        }
        if (search.getGoodsId() != null) {
            criteria.andIdEqualTo(search.getGoodsId());
        }

        List<MarketGoods> marketGoods = marketGoodsMapper.selectByExample(marketGoodsExample, info.getOrder());
        PageInfo<MarketGoods> pageInfo = new PageInfo<>(marketGoods);
        return CommonData.data(pageInfo);
    }

    /*
     * @author 李海云
     * @description 商品详细
     * @date 2022/7/18 9:10
     * @param id
     * @return CommonData 商品详细信息
     */
    @Override
    public GoodsDetailVO queryGoodsById(Integer id) {

        MarketGoods marketGoods = marketGoodsMapper.selectByPrimaryKey(id);

        MarketGoodsAttributeExample mgae = new MarketGoodsAttributeExample();
        MarketGoodsAttributeExample.Criteria criteria1 = mgae.createCriteria().andGoodsIdEqualTo(id);
        List<MarketGoodsAttribute> marketGoodsAttributes = attributeMapper.selectByExample(mgae);

        MarketGoodsSpecificationExample msse = new MarketGoodsSpecificationExample();
        MarketGoodsSpecificationExample.Criteria criteria2 = msse.createCriteria().andGoodsIdEqualTo(id);
        List<MarketGoodsSpecification> marketGoodsSpecifications = specificationMapper.selectByExample(msse);

        MarketGoodsProductExample mgpe = new MarketGoodsProductExample();
        MarketGoodsProductExample.Criteria criteria3 = mgpe.createCriteria().andGoodsIdEqualTo(id);
        List<MarketGoodsProduct> marketGoodsProducts = productMapper.selectByExample(mgpe);


        GoodsDetailVO goodsDetailVO = new GoodsDetailVO();

        goodsDetailVO.setGoods(marketGoods);
        goodsDetailVO.setAttributes(marketGoodsAttributes);
        goodsDetailVO.setSpecifications(marketGoodsSpecifications);
        goodsDetailVO.setProducts(marketGoodsProducts);

        return goodsDetailVO;
    }

    /*
     * @author 李海云
     * @description 品牌 类目获取
     * @date 2022/7/18 9:10
     * @param id
     * @return CommonData 商品详细信息
     */
    @Override
    public CatAndBrandVO queryCatAndBrand() {
        CatAndBrandVO catAndBrandVO = new CatAndBrandVO();
        MarketBrandExample mbe = new MarketBrandExample();
        mbe.clear();
        List<MarketBrand> marketBrands = brandMapper.selectByExample(mbe);
        LinkedList<AdminVLVO> list1 = new LinkedList<>();
        for (MarketBrand marketBrand : marketBrands) {
            AdminVLVO vlvo = new AdminVLVO();
            vlvo.setLabel(marketBrand.getName());
            vlvo.setValue(String.valueOf(marketBrand.getId()));
            list1.add(vlvo);
        }
        catAndBrandVO.setBrandList(list1);

        MarketCategoryExample mce = new MarketCategoryExample();
        mce.clear();
        List<MarketCategory> marketCategories = categoryMapper.selectByExample(mce);
        LinkedList<AdminMarketCategoryVO> list2 = new LinkedList<>();
        for (MarketCategory marketCategory : marketCategories) {
            AdminMarketCategoryVO marketCategoryVO = new AdminMarketCategoryVO();
            marketCategoryVO.setLabel(marketCategory.getName());
            marketCategoryVO.setValue(marketCategory.getId());

            LinkedList<AdminVLVO> children = new LinkedList<>();

            mce.clear();
            mce.createCriteria().andPidEqualTo(marketCategory.getId());
            List<MarketCategory> childrens = categoryMapper.selectByExample(mce);
            for (MarketCategory category : childrens) {
                AdminVLVO temp = new AdminVLVO();
                temp.setLabel(category.getName());
                temp.setValue(String.valueOf(category.getId()));
                children.add(temp);
            }
            marketCategoryVO.setChildren(children);
            list2.add(marketCategoryVO);
        }

        catAndBrandVO.setCategoryList(list2);

        return catAndBrandVO;
    }


    /*
     * @author 李海云
     * @description 更新商品
     * @date 2022/7/18 9:10
     * @param id
     * @return
     */
    @Override
    @Transactional
    public void updateGoods(AdminUPDataBO up) {
        Integer gid = Integer.valueOf(up.getGoods().getId());
        //删除
        MarketGoodsSpecificationExample sgse = new MarketGoodsSpecificationExample();
        sgse.createCriteria().andGoodsIdEqualTo(gid);
        MarketGoodsProductExample mgpe = new MarketGoodsProductExample();
        mgpe.createCriteria().andGoodsIdEqualTo(gid);
        MarketGoodsAttributeExample mgae = new MarketGoodsAttributeExample();
        mgae.createCriteria().andGoodsIdEqualTo(gid);


        marketGoodsMapper.deleteByPrimaryKey(gid);
        specificationMapper.deleteByExample(sgse);
        productMapper.deleteByExample(mgpe);
        attributeMapper.deleteByExample(mgae);
        //插入
        up.getGoods().setUpdateTime(new Date());
        if (up.getGoods().getBrandId() == null) {
            up.getGoods().setBrandId(0);
        }
        marketGoodsMapper.insert(up.getGoods());

        for (MarketGoodsAttribute attribute : up.getAttributes()) {
            attribute.setGoodsId(gid);
            attributeMapper.insert(attribute);
        }
        for (MarketGoodsProduct attribute : up.getProducts()) {
            attribute.setGoodsId(gid);
            productMapper.insert(attribute);
        }
        for (MarketGoodsSpecification attribute : up.getSpecifications()) {
            attribute.setGoodsId(gid);
            specificationMapper.insert(attribute);
        }

    }

    /*
     * @author 李海云
     * @description 删除商品
     * @date 2022/7/18 9:10
     * @param goods
     * @return
     */
    @Override
    @Transactional
    public void deleteGoods(MarketGoods goods) {
        goods.setDeleted(true);
        goods.setUpdateTime(new Date());
        marketGoodsMapper.updateByPrimaryKey(goods);

        //     //幂等删除
        MarketGoodsProductExample mgpe = new MarketGoodsProductExample();
        mgpe.createCriteria().andGoodsIdEqualTo(goods.getId());
        List<MarketGoodsProduct> products = productMapper.selectByExample(mgpe);
        if (products == null) {
        } else {
            for (MarketGoodsProduct product : products) {
                MarketGoodsProduct nProduct = new MarketGoodsProduct();
                BeanUtils.copyProperties(product, nProduct);
                nProduct.setDeleted(true);
                productMapper.updateByPrimaryKey(nProduct);
            }
        }
        MarketGoodsSpecificationExample mgse = new MarketGoodsSpecificationExample();
        mgse.createCriteria().andGoodsIdEqualTo(goods.getId());
        List<MarketGoodsSpecification> specifications = specificationMapper.selectByExample(mgse);
        if (specifications == null) {
        } else {
            for (MarketGoodsSpecification product : specifications) {
                MarketGoodsSpecification nSpecification = new MarketGoodsSpecification();
                BeanUtils.copyProperties(product, nSpecification);
                nSpecification.setDeleted(true);
                specificationMapper.updateByPrimaryKey(nSpecification);
            }
        }
        MarketGoodsAttributeExample mgae = new MarketGoodsAttributeExample();
        mgae.createCriteria().andGoodsIdEqualTo(goods.getId());
        List<MarketGoodsAttribute> attributes = attributeMapper.selectByExample(mgae);
        if (attributes == null) {
        } else {
            for (MarketGoodsAttribute product : attributes) {
                MarketGoodsAttribute nAttribute = new MarketGoodsAttribute();
                BeanUtils.copyProperties(product, nAttribute);
                nAttribute.setDeleted(true);
                attributeMapper.updateByPrimaryKey(nAttribute);
            }
        }

    }

    /*
     * @author 李海云
     * @description 文件上传（图片）
     * @date 2022/7/18 9:30
     * @param file
     * @return
     */
    @Override
    @Transactional
    public MarketStorage create(MultipartFile file) {

        String fileName = file.getOriginalFilename();
        String suffix = null;
        String[] split = fileName.split("\\.");
        if (split != null && split.length > 1) {
            suffix = split[split.length - 1];
        }
        String uuid = UUID.randomUUID().toString();
        fileName = uuid + "." + suffix;
        int hashcode = fileName.hashCode();
        String hexString = Integer.toHexString(hashcode);
        char[] chars = hexString.toCharArray();
        String basePath = "image";
        for (char aChar : chars) {
            basePath = basePath + "/" + aChar;
        }
        File saveFile = new File(PicURL.localMap, basePath + "/" + fileName);
        try {
            if (!saveFile.exists()) {
                saveFile.mkdirs();
            }
            file.transferTo(saveFile);
        } catch (IOException e) {
            e.printStackTrace();
        }

        MarketStorage marketStorage = new MarketStorage();
        marketStorage.setAddTime(new Date());
        marketStorage.setUpdateTime(new Date());
        marketStorage.setType(file.getContentType());
        marketStorage.setDeleted(false);
        marketStorage.setSize(file.getSize());
        marketStorage.setKey(fileName);
        marketStorage.setName(uuid);

        marketStorage.setUrl(PicURL.urlPro + PicURL.urlMap + basePath + "/" + fileName);
        storageMapper.insert(marketStorage);
        return marketStorage;
    }

    /*
     * @author 李海云
     * @description 商品增加
     * @date 2022/7/18 15:30
     * @param up
     * @return
     */
    @Override
    public int createGoods(AddGoodBO up) {

        try {

            MarketGoods goods = up.getGoods();

            for (Product2 product : up.getProducts()) {

                double v = 0;
                double v2 = 0;
                double v3 = 0;
                try {
                    v = product.getPrice().doubleValue();
                     v2 = goods.getCounterPrice().doubleValue();
                //    v3 = goods.getRetailPrice().doubleValue();

                } catch (Exception e) {
                    return -1;
                }
                if (product.getNumber() < 0 || v < 0 || v2 < 0 || v3 < 0) {
                    return 0;
                }
           }


            // System.out.println(goods);
            marketGoodsMapper.insert(goods);


            if (goods.getKeywords() != null) {

                MarketKeyword marketKeyword = new MarketKeyword();
                System.out.println(goods.getKeywords());
                marketKeyword.setKeyword(goods.getKeywords());
                keywordMapper.insert(marketKeyword);
            }


            List<MarketGoodsAttribute> attributes = up.getAttributes();

            if (goods.getKeywords() != null) {

                MarketKeyword marketKeyword = new MarketKeyword();
                marketKeyword.setKeyword(goods.getKeywords());
                keywordMapper.insert(marketKeyword);
            }


            for (MarketGoodsAttribute attribute : attributes) {
                MarketGoodsAttribute marketGoodsAttribute = new MarketGoodsAttribute();
                BeanUtils.copyProperties(attribute, marketGoodsAttribute);
                marketGoodsAttribute.setGoodsId(goods.getId());
                attributeMapper.insert(marketGoodsAttribute);
            }
            List<MarketGoodsProduct> products = up.change();
            for (MarketGoodsProduct product : products) {
                MarketGoodsProduct marketGoodsProduct = new MarketGoodsProduct();
                BeanUtils.copyProperties(product, marketGoodsProduct);
                marketGoodsProduct.setGoodsId(goods.getId());
                productMapper.insert(marketGoodsProduct);
            }
            List<MarketGoodsSpecification> specifications = up.getSpecifications();
            for (MarketGoodsSpecification specification : specifications) {
                MarketGoodsSpecification marketGoodsSpecification = new MarketGoodsSpecification();
                BeanUtils.copyProperties(specification, marketGoodsSpecification);
                marketGoodsSpecification.setGoodsId(goods.getId());
                specificationMapper.insert(marketGoodsSpecification);
            }

        } catch (Exception e) {
            return 0;
        }
        return 1;
    }
}
